<script>
import {isAuthenticated} from "./authService.js";
export default {
  data(){
    return {
      username: localStorage.getItem("username"),
      isAuthenticated:isAuthenticated()
    }
  },
  methods: {
    logout() {
      // 清除本地存储中的 JWT 和用户名
      localStorage.removeItem('jwtToken');
      localStorage.removeItem('username');
      this.username = '';
      this.isAuthenticated = false;
      this.$router.push('/'); // 重定向
    }
  },
  watch: {
    // 监听路由变化，确保在导航时重新检查认证状态
    '$route': {
      handler() {
        this.username = localStorage.getItem("username");
        this.isAuthenticated = isAuthenticated();
      },
      immediate: true // 立即执行一次，确保首次加载时也触发
    }
  }
}


</script>

<template>
  <!--添加导航栏-->
  <div class="container">
    <div class="nav">
      <nav>
        <!--      blogs链接-->
        <router-link to="/">主页</router-link>
        <router-link to="/blogs">博客</router-link>
        <ul class="nav-links">
          <li v-if="!isAuthenticated">
            <router-link to="/login">登录</router-link>
          </li>
          <li v-if="!isAuthenticated">
            <router-link to="/register">注册</router-link>
          </li>
          <li v-if="isAuthenticated">
            <router-link to="/createblog">发表博客</router-link>
          </li>
          <li v-if="isAuthenticated">
            <span>欢迎, {{ username }}</span>
          </li>
          <li v-if="isAuthenticated">
            <button @click="logout">登出</button>
          </li>
        </ul>
        <a></a>
      </nav>
    </div>
    <div class="content">
      <!--      用于渲染与当前路由匹配的组件-->
      <router-view></router-view>
    </div>
  </div>
</template>

<style scoped>
.nav {
  width: 1200px;
  height: auto;
  padding: 10px;
  background-color: #d4d7de;

}
nav{
  display: flex;/* 水平排列 */
  align-items: center; /* 垂直居中对齐 */
}

.nav-links {
  display: flex;
  list-style: none;
}
</style>

